<template>
  <el-select
    ref="dragSelect"
    v-model="selectVal"
    v-bind="$attrs"
    class="drag-select"
    multiple
    v-on="$attrs"
  >
    <slot />
  </el-select>
</template>

<script setup name="DragSelect">
import Sortable from 'sortablejs'
import { getCurrentInstance, onMounted } from 'vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
  value: {
    type: Array,
    required: true,
  },
})
const emit = defineEmits(['input'])

const selectVal = computed({
  get() {
    return [...props.value]
  },
  set(val) {
    emit('input', [...val])
  },
})

onMounted(() => {
  setSort()
})
function setSort () {
  const el = proxy.$refs.dragSelect.$el.querySelectorAll(
    '.el-select__tags > span'
  )[0]
  proxy.sortable = Sortable.create(el, {
    ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
    setData: function (dataTransfer) {
      dataTransfer.setData('Text', '')
      // to avoid Firefox bug
      // Detail see : https://github.com/RubaXa/Sortable/issues/1012
    },
    onEnd: (evt) => {
      const targetRow = props.value.splice(evt.oldIndex, 1)[0]
      props.value.splice(evt.newIndex, 0, targetRow)
    },
  })
}
</script>

<style scoped>
.drag-select :deep(.sortable-ghost) {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}

.drag-select :deep(.el-tag) {
  cursor: pointer;
}
</style>
